package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.common.annotation.LogAnno;
import com.example.common.result.Result;
import com.example.controller.base.BaseController;
import com.example.entity.Position;
import com.example.entity.User;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author daiweiyuan
 * @date 2022/4/16
 */
@RestController
@RequestMapping("/position")
public class PositionController extends BaseController {
    
    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Integer id) {
        return Result.ok().data(positionService.getById(id));
    }

    @GetMapping("/tree")
    @PreAuthorize("hasAuthority('sys:position:list')")
    public Result tree() {
        List<Position> positions = positionService.tree();
        return Result.ok().data(positions);
    }
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:position:list')")
    public Result list() {
        List<Position> positions = positionService.list(new QueryWrapper<Position>().orderByAsc("level"));
        return Result.ok().data(positions);
    }
    @GetMapping("/level")
    @PreAuthorize("hasAuthority('sys:position:edit')")
    public Result level() {
        List<Position> list = positionService.list();
        List<Integer> levels = list.stream().map(Position::getLevel).collect(Collectors.toList());
        return Result.ok().data(levels.stream().distinct().collect(Collectors.toList()));
    }

    @LogAnno(operateType = "新增职位")
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:position:add')")
    public Result save(@Validated @RequestBody Position position) {
        position.setLevel(position.getParentLevel()+1);
        positionService.save(position);
        return Result.created().data(position);
    }

    @LogAnno(operateType = "更新职位")
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:position:edit')")
    public Result update(@Validated @RequestBody Position position) {
        position.setLevel(position.getParentLevel()+1);
        positionService.updateById(position);
        return Result.update().data(position);
    }

    @LogAnno(operateType = "删除职位")
    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:position:del')")
    public Result delete(@PathVariable Integer id) {
        positionService.removeById(id);
        userService.update(new UpdateWrapper<User>().set("position_id",null).eq("position_id",id));
        return Result.ok();
    }
}
